package controllers

import (
	"day02/models"
	beego "github.com/beego/beego/v2/server/web"
)

type OrderController struct {
	beego.Controller
}

type Res struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

type PageCount struct {
	Data  interface{} `json:"data"`
	Count int64
}

func (c *OrderController) List() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)

	i := (page - 1) * size

	var order []models.Order

	if err := models.DB.Offset(i).Limit(size).Find(&order).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "查询失败",
		}
		c.ServeJSON()
		return
	}

	var count int64
	models.DB.Model(&order).Count(&count)

	c.Data["json"] = Res{
		Code: 200,
		Data: PageCount{
			Data:  order,
			Count: count,
		},
		Message: "查询成功",
	}
	c.ServeJSON()
	return
}
